package cn.lzy.demo.service;

import cn.lzy.demo.dao.AccountDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @Description
 * @Author lzy
 * @Date 2023/12/27 23:02
 * @Version
 **/
@Service
public class AccountService {

    @Autowired
    private AccountDao accountDao;
    @Autowired
    private PlatformTransactionManager transactionManager;
    @Autowired
    private TransactionTemplate transactionTemplate;


    /**
     * 转钱
     * （使用事务-PlatformTransactionManager）
     * @param from  来源帐号
     * @param to    目标帐号
     * @param money 金额
     */
    public void transferMoney(String from, String to, Double money) {
        // 默认事务定义
        DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
        // 获取事务
        TransactionStatus status = transactionManager.getTransaction(transactionDefinition);
        try {
            accountDao.minusMoney(from, money);
            // 报错模拟代码
//            int i = 1 / 0;
            accountDao.addMoney(to, money);
            // 提交事务
            transactionManager.commit(status);
        } catch (Exception e) {
            System.err.println("程序出错！！！");
            // 回滚事务
            transactionManager.rollback(status);
        }
    }


    /**
     * 转钱
     * （使用事务-TransactionTemplate）
     * @param from
     * @param to
     * @param money
     */
    public void transferMoney2(String from, String to, Double money) {

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                try {
                    accountDao.minusMoney(from, money);
                    // 报错模拟代码
                    int i = 1 / 0;
                    accountDao.addMoney(to, money);

                    // 提交事务（该行代码可以不要）
                    transactionStatus.isCompleted();
                } catch (Exception e) {
                    System.err.println("程序出错！！！");
                    // 回滚事务
                    transactionStatus.setRollbackOnly();
                }
            }
        });
    }

}
